<template>
  <div class="client-m-index">
    <section
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <Search
        :type="1"
        :value="[props.accountType]"
        :pageParam="{ page: param.page, size: param.size }"
        :placeholder="'请输入关键字进行搜索'"
        @searchResult="searchResult"
      />
      <el-button
        v-if="accountType !== 0"
        type="primary"
        style="margin-bottom: 1em"
        @click="isShowAddUserDialog = true"
        >新增</el-button
      >
    </section>
    <el-table
      style="height: 100%"
      :data="userList"
      stripe
      empty-text="暂无数据"
      show-overflow-tooltip
    >
      <el-table-column prop="avatar" label="用户头像" width="100">
        <template #default="scoped">
          <el-image
            class="image"
            loading="lazy"
            :src="scoped.row.avatar"
            :preview-src-list="[scoped.row.avatar]"
            preview-teleported
            hide-on-click-modal
          >
            <template #error>
              <el-image
                class="image"
                loading="lazy"
                :src="errorImageUrlConstant"
                :preview-src-list="[errorImageUrlConstant]"
                preview-teleported
                hide-on-click-modal
              />
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="account" label="用户账号" width="180" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="accountType" label="用户类型" width="180">
        <template #default="scoped">
          <el-tag v-if="scoped.row.accountType === 0" type="primary" round>
            <span>玩家</span>
          </el-tag>
          <Tag
            v-else-if="scoped.row.accountType === 1"
            name="独立游戏作者"
            color="#9b59b6"
          />
          <Tag
            v-else-if="scoped.row.accountType === 2"
            name="游戏开发商"
            color="#3375b9"
          />
          <el-tag v-else-if="scoped.row.accountType === 3" type="success" round>
            <span>平台管理员</span>
          </el-tag>
          <el-tag v-else type="danger" round>
            <span>待确定</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="telephone" label="电话号码" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column
        fixed="right"
        label="操作"
        width="auto"
        min-width="180px"
      >
        <template #default="scoped">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleDetail(scoped.row, 0)"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(scoped.row)"
          >
            编辑</el-button
          >
          <el-button
            link
            type="danger"
            size="small"
            :disabled="scoped.row.status === 1 || isDisabled(/* scoped.row */)"
            @click="handleSetAccountStatus(scoped.row, 1)"
            >停用</el-button
          >
          <el-button
            link
            type="success"
            size="small"
            :disabled="scoped.row.status === 0 || isDisabled(/* scoped.row */)"
            @click="handleSetAccountStatus(scoped.row, 0)"
            >启用</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination
        layout="sizes, prev, pager, next, jumper"
        :page-count="pageCount"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-config-provider>
  </div>
  <Info :userInfo="userInfo" />
  <Edit
    :editUserInfo="editUserInfo"
    @updateUserList="
      () => {
        getUserListData(param);
      }
    "
  />
  <el-dialog
    v-model="isShowAddUserDialog"
    :title="`新建${accountType === 1 ? '游戏开发者' : '管理员'}信息`"
    width="40%"
  >
    <el-form label-position="left" label-width="auto">
      <el-form-item label="用户头像">
        <el-upload
          v-if="isShowAddUserDialog"
          :http-request="handleUpload"
          list-type="picture-card"
          v-model="newUserInfo.avatar"
          :limit="1"
          accept="image/*"
          :class="{ hide_box: newUserInfo.avatar != '' }"
          :on-remove="() => (newUserInfo.avatar = '')"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户账号">
        <el-input v-model="newUserInfo.account"></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="newUserInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="用户类型">
        <el-select
          placeholder="请选择用户类型"
          v-model="newUserInfo.accountType"
        >
          <el-option
            v-for="item of accountTypeOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="newUserInfo.email"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="newUserInfo.telephone"></el-input>
      </el-form-item>
      <el-form-item label="账户密码">
        <el-input
          type="password"
          v-model="newUserInfo.password"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="addUser" style="margin-right: 10px">
        确定
      </el-button>
      <el-button
        @click="
          isShowAddUserDialog = false;
          newUserInfo = { ...emptyUserInfo };
        "
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getUserListApi, registerApi } from "@/apis/user.ts";
import { setAccountStatusApi } from "@/apis/admin";
import {
  ElLoading,
  ElConfigProvider,
  ElMessageBox,
  ElMessage,
} from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import Edit from "./edit.vue";
import Info from "./info.vue";
import { errorImageUrlConstant } from "@/constant";
import Search from "@/components/sreach/index.vue";
import Tag from "@/components/tag/index.vue";
import { uploadApi } from "@/apis/upload";

const props = defineProps({
  accountType: {
    type: Number,
    default: 0,
  },
});

const userList = ref([]);

const pageCount = ref(0);

const param = ref({
  page: 1,
  size: 10,
  accountType: 0,
});

const userInfo = ref({
  isShow: false,
  // 点击操作类型： 0: 详情 1: 编辑
  handleType: 0,
  info: {} as any,
});

const editUserInfo = ref({
  isShow: false,
  info: {} as any,
});

const newUserInfo = ref({
  avatar: "",
  account: "",
  username: "",
  accountType: props.accountType,
  email: "",
  telephone: "",
  password: "111111",
});

const emptyUserInfo = { ...newUserInfo.value };

const isShowAddUserDialog = ref(false);

const accountTypeOptions = computed(() => {
  return props.accountType === 1
    ? [
        {
          id: 1,
          label: "独立游戏作者",
        },
        {
          id: 2,
          label: "游戏开发商",
        },
      ]
    : [
        {
          id: 3,
          label: "平台管理员",
        },
        {
          id: 4,
          label: "终端管理员",
        },
      ];
});

function searchResult(data: any) {
  userList.value = data.records;
}

function handleEdit(row: any) {
  // console.log(row);

  editUserInfo.value.isShow = true;
  editUserInfo.value.info = row;
}

function handleDetail(row: any, handleType: number) {
  // console.log(row);

  userInfo.value.isShow = true;
  userInfo.value.handleType = handleType;
  userInfo.value.info = row;
}

async function handleSizeChange(val: number) {
  param.value.size = val;
  await getUserListData(param.value);
}

async function handleCurrentChange(val: number) {
  param.value.page = val;
  await getUserListData(param.value);
}

async function getUserListData(param: any) {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  try {
    const res = await getUserListApi(param);
    userList.value = res.data.records;
    pageCount.value = res.data.pages;
  } catch (error) {
    console.log(error);
  } finally {
    // userList.value.forEach((item: any) => {
    //   if (item.avatar === null) {
    //     item.avatar = errorImageUrlConstant;
    //   }
    // });
    loading.close();
  }
}
async function setAccountStatus(param: any) {
  try {
    const res: any = await setAccountStatusApi(param);
    if (res.code === 0) {
      ElMessage.success("操作成功");
      return true;
    } else {
      ElMessage.error("操作失败");
      return false;
    }
  } catch (error) {
    ElMessage.error("操作失败");
    return false;
  }
}

function isDisabled(/* row: any */) {
  if (props.accountType === 0 || props.accountType === 1) {
    return false;
  } else {
    return true;
  }
}

async function handleSetAccountStatus(row: any, status: any) {
  const formData = new FormData();
  formData.append("userId", row.id);
  formData.append("status", status);

  let changeMessage = "";
  if (status === 1) {
    changeMessage = "<span style='color:var(--el-color-danger);'>停用</span>";
  } else if (status === 0) {
    changeMessage = "<span style='color:var(--el-color-success);'>启用</span>";
  }

  try {
    await ElMessageBox.confirm(
      `确认 ${changeMessage} 用户 ${row.username} 的账户吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
      }
    );
    const res: any = await setAccountStatus(formData);
    if (res) {
      row.status = status;
    }
  } catch (error) {
    ElMessage.info("操作取消");
  }
}

async function handleUpload({ file }: any) {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const res: any = await uploadApi(formData);
    if (res.code === 0) {
      newUserInfo.value.avatar = res.data;
      ElMessage.success("上传成功");
    } else {
      ElMessage.error("上传失败");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("上传失败");
  }
}

async function addUser() {
  try {
    const res: any = await registerApi(newUserInfo.value);
    if (res.code === 0) {
      isShowAddUserDialog.value = false;
      newUserInfo.value = { ...emptyUserInfo };
      getUserListData(param.value);
      ElMessage.success("新增用户成功");
    } else {
      ElMessage.error("新增用户失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
}

onMounted(async () => {
  param.value.accountType = props.accountType as number;
  await getUserListData(param.value);
});
</script>

<style scoped>
.client-m-index {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* align-items: center; */
  justify-content: space-between;
}
.image {
  width: 100%;
  aspect-ratio: 1 / 1;
  border-radius: 50%;
}
.pagination {
  position: relative;
  bottom: 0;
  /* height: 10vh; */
  margin: 10px auto;
}
.hide_box :deep(.el-upload--picture-card) {
  display: none;
}
</style>
